import Vue from 'vue'
import VueRouter from 'vue-router'
import Store from '../store'

Vue.use(VueRouter)

const routes = [{
  path: '/',
  redirect: '/home'
}, {
  path: '/home',
  name: 'Home',
  component: () => import('../views/Home/index'),
  redirect: '/home/exhibition',
  children: [{
    path: 'exhibition',
    name: 'Exhibition',
    component: () => import('../views/Exhibition/index'),
    meta: {requireAuth: true}
  }, {
    path: 'manage',
    name: 'Manage',
    component: () => import('../views/Manage/index'),
    meta: {requireAuth: true}
  }]
}, {
  path: '/login',
  name: 'Login',
  component: () => import('../views/Login/index')
}]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    Store.dispatch('user/getConfig').then(() => {
      next()
    }).catch(() => {
      next({
        path: '/login'
      })
    })
  } else {
    next()
  }
})

export default router
